<?php

/**
 * This is the model class for table "funcionario".
 *
 * The followings are the available columns in table 'funcionario':
 * @property integer $id
 * @property integer $pessoa_id
 * @property integer $polo_id
 * @property string $pis_pasep
 * @property string $tipo
 * @property string $horario
 * @property string $curso_formacao
 * @property string $instituicao_ensino
 * @property string $observacao
 *
 * The followings are the available model relations:
 * @property Aluno[] $alunos
 * @property Polo $polo
 * @property Pessoa $pessoa
 * @property TblUser[] $tblUsers
 * @property Turma[] $turmas
 * @property TurmaHasAluno[] $turmaHasAlunos
 * @property TurmaHasFuncionario[] $turmaHasFuncionarios
 */
class Funcionario extends CActiveRecord
{
	public $search_nome;
	public $search_email;

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'funcionario';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
				array('polo_id, tipo, horario', 'required','message'=>'Campo {attribute} esta vazio.'),
				array('pessoa_id, polo_id', 'numerical', 'integerOnly'=>true ,'message'=>'Campo {attribute} deve conter apenas numeros.'),
				array('pis_pasep, tipo, horario', 'length', 'max'=>45),
				array('curso_formacao, instituicao_ensino, observacao', 'length', 'max'=>250),
				// The following rule is used by search().
				// @todo Please remove those attributes that should not be searched.
				array('id, pessoa_id, polo_id, pis_pasep, tipo, horario, curso_formacao, instituicao_ensino, observacao, search_nome, search_email', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
				'alunos' => array(self::HAS_MANY, 'Aluno', 'atendente_id'),
				'polo' => array(self::BELONGS_TO, 'Polo', 'polo_id'),
				'pessoa' => array(self::BELONGS_TO, 'Pessoa', 'pessoa_id'),
				'tblUsers' => array(self::HAS_MANY, 'TblUser', 'funcionario_id'),
				'turmas' => array(self::HAS_MANY, 'Turma', 'responsavel_id'),
				'turmaHasAlunos' => array(self::HAS_MANY, 'TurmaHasAluno', 'responsavel_id'),
				'turmaHasFuncionarios' => array(self::HAS_MANY, 'TurmaHasFuncionario', 'funcionario_id'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
				'id' => 'ID',
				'pessoa_id' => 'Pessoa',
				'polo_id' => 'Pólo',
				'pis_pasep' => 'Pis/Pasep',
				'tipo' => 'Tipo',
				'horario' => 'Horário',
				'curso_formacao' => 'Curso de Formação',
				'instituicao_ensino' => 'Instituição de Ensino',
				'observacao' => 'Observação',
				'search_nome' => 'Nome',
				'search_email' => 'Email',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 *
	 * Typical usecase:
	 * - Initialize the model fields with values from filter form.
	 * - Execute this method to get CActiveDataProvider instance which will filter
	 * models according to data in model fields.
	 * - Pass data provider to CGridView, CListView or any similar widget.
	 *
	 * @return CActiveDataProvider the data provider that can return the models
	 * based on the search/filter conditions.
	 */
	public function search()
	{
		// @todo Please modify the following code to remove attributes that should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id);
		$criteria->with=array('pessoa', 'polo');
		if(strlen($this->search_nome))
			$criteria->addSearchCondition('pessoa.nome',$this->search_nome,true);

		if(strlen($this->search_email))
			$criteria->addSearchCondition('pessoa.email', $this->search_email, true);

		$criteria->compare('pessoa_id',$this->pessoa_id);
		$criteria->compare('polo_id',$this->polo_id);
		$criteria->compare('pis_pasep',$this->pis_pasep,true);
		$criteria->compare('tipo',$this->tipo,true);
		$criteria->compare('horario',$this->horario,true);
		$criteria->compare('curso_formacao',$this->curso_formacao,true);
		$criteria->compare('instituicao_ensino',$this->instituicao_ensino,true);
		$criteria->compare('observacao',$this->observacao,true);

		return new CActiveDataProvider($this, array(
				'criteria'=>$criteria,
				'pagination'=>array(
						'pageSize'=>15,
				),
		));
	}

	public function save($runValidation = true, $attributes = NULL) {
		if($this->pessoa != null) {
			$this->pessoa->save();
		}

		if($this->tblUsers != null) {
			$this->tblUsers->email = $this->pessoa->email;
			$this->tblUsers->save();
		}
		parent::save();
	}

	public function deleteData() {

		$turmas = Turma::model()->findAllByAttributes(array('responsavel_id'=>$this->id));
		if($turmas != null && !empty($turmas)) {
			foreach($turmas as $turma) {
				$turma->responsavel_id = null;
				$turma->save();
			}
		}

		$avaliacoes = AvaliacaoDiaria::model()->findAllByAttributes(array('responsavel_id'=>$this->id));
		if($avaliacoes != null && !empty($avaliacoes)) {
			foreach($avaliacoes as $avaliacao) {
				$avaliacao->responsavel_id = null;
				$avaliacao->save();
			}
		}

		if($this->pessoa != null) {
			$this->pessoa->delete();
		}


		if($this->tblUsers != null) {
			$this->tblUsers->delete();
		}
		$this->delete();
	}


	public static function addAdmin() {
		$query = file_get_contents(YiiBase::getPathOfAlias('webroot').'/protected/data/funcionario_insert.sql');
		$transaction=Yii::app()->db->beginTransaction();
		try
		{
			Yii::app()->db->createCommand($query)->execute();
			//.... other SQL executions
			$transaction->commit();
		}
		catch(Exception $e) // an exception is raised if a query fails
		{
			$transaction->rollback();
		}
	}

	/**
	 * Returns the static model of the specified AR class.
	 * Please note that you should have this exact method in all your CActiveRecord descendants!
	 * @param string $className active record class name.
	 * @return Funcionario the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}
}
